<template>
    <div class="tablelist">
        <Dialog :app-dialog="newRuler">
            <el-form :model="addGroupingForm" label-width="95px" class="demo-ruleForm" :size="formSize">
                <el-form-item label="敏感词" required>
                    <el-input v-model="addGroupingForm.words_name" placeholder="请输入敏感词" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="tips">每个敏感词最多支持15个字，同时新建多个敏感词时，请用“空格”隔开</div>
                </el-form-item>

                <el-form-item label="敏感词分组" required>
                    <el-cascader
                        ref="cascaderRef"
                        v-model="addGroupingForm.group_id"
                        style="width: 320px"
                        :options="groupData"
                        :props="props"
                        placeholder="请选择分组"
                        @change="orgChange" />
                </el-form-item>
                <el-form-item label="敏感词状态">
                    <el-switch v-model="addGroupingForm.status" />
                </el-form-item>
            </el-form>
        </Dialog>
        <!-- //删除 开启 关闭弹框 -->
        <Dialog :app-dialog="appDialog">
            <div class="content">{{ content }}</div>
        </Dialog>
    </div>
    <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="emptyFunc" @expand="getTableH" />
    <ZwTable
        ref="tableRef"
        class="table-box"
        :option="tableOption"
        tab-h="initial"
        :row-key="getRowKey"
        :fetch-params="state.searchParams"
        :fetch-api="fetchApi()"
        :close-loading="true"
        @select-all="onSelectAll"
        @select="onSelect">
        <template #headerOperate>
            <el-button v-auth="'BATCH_OPEN'" :disabled="allids.length == 0" @click="operate(1)"> 批量开启 </el-button>
            <el-button v-auth="'BATCH_CLOSE'" :disabled="allids.length == 0" @click="operate(2)"> 批量关闭 </el-button>
            <el-button v-auth="'BATCH_DEL'" :disabled="allids.length == 0" @click="operate(3)"> 批量删除 </el-button>
            <el-button v-auth="'NEW_SENSITIVE'" type="primary" @click="openWord">新增敏感词</el-button>
        </template>
    </ZwTable>
</template>
<script setup lang="tsx">
import { ref, onMounted, watch, reactive, computed, nextTick } from 'vue';
import Dialog from '@/components/Dialog.vue';
// import ZWPagination from '@/components/ZWPagination.vue'
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { store } from '@/store';
import { ElMessage } from 'element-plus';
import {
    newSensitive,
    getSensitivelist,
    deleteSensitivelist,
    openSensitivelist,
    closeSensitivelist
} from '@/api/employe/riskmonitoring/sensitiveWord';
import { tableH, reSize } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { getGroupList } from '@/api/concreation';
import { getSetionId } from '@/utils/utils';
import { ElButton, ElPopover } from 'element-plus';
import { startLoading, endLoading } from '@/utils/request';

const pro = defineProps(['selectid']);
const emit = defineEmits(['submit', 'cancel', 'init', 'refreshData']);
const allids = ref([]); //批量删除列表
const ids = ref([]); //删除列表
const content = ref('确定开启所选关键词吗?');
const type = ref(20);
const currentParams = ref<any>(null);
const searchData = reactive({ keywords: '', status: '全部' });
const paginationRef = ref(null);
const cascaderRef: any = ref(null); // 选择分组ref
const tableRef = ref(null);
const tabH = ref('500px');
// 表格列表
const tableData = ref([]);
// 分组 tree
const groupData = ref([]);
// 分组列表
const group_id = () => {
    return store.getters['content/group'];
};
const page = reactive({
    page: 1,
    page_size: 15
});
const addGroupingForm = reactive({
    group_id: '', //所属分组ID
    words_name: '', //敏感词
    status: 1
});
const props = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};

const searchOption = computed(() => {
    return [
        {
            label: '敏感词',
            name: 'keywords',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '敏感词搜索'
        },
        {
            label: '状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: '0' },
                            { name: '关闭', id: '2' },
                            { name: '开启', id: '1' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'words_name',
        label: '敏感词',
        width: 140
    },
    {
        prop: 'staff_touch_nums',
        label: '员工触发次数',
        width: 140
    },
    {
        prop: 'contact_touch_nums',
        label: '客户触发次数',
        width: 130
    },
    {
        label: '状态',
        render({ row, column, index }) {
            return <div> {row.status == 2 ? '关闭' : '启用'}</div>;
        }
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 120
    },
    {
        prop: 'creater_name',
        label: '创建人',
        width: 120
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 160
    },
    {
        prop: 'operate',
        label: '操作',
        align: 'left',
        fixed: 'right',
        width: 220,
        isOperate: true,
        renderOperate({ row, column, index }) {
            const Reference = () => (
                <span>
                    <ElButton
                        vShow={row.status == 1 && row.is_used == 1}
                        size="small"
                        disabled
                        vAuth={'ADD_CHILD_GROUP'}>
                        关闭
                    </ElButton>
                </span>
            );
            const Reference2 = () => (
                <span style="margin-left: 10px">
                    <ElButton vShow={row.is_used == 1} size="small" disabled vAuth={'DEL'}>
                        删除
                    </ElButton>
                </span>
            );
            return (
                <div>
                    <ElPopover
                        placement="top-start"
                        width={200}
                        vSlots={{ reference: Reference }}
                        trigger="hover"
                        content="当前敏感词已在监控规则中配置，暂不可关闭。"></ElPopover>
                    <ElButton
                        size="small"
                        onClick={() => closeClick(row, 1)}
                        vShow={row.status == 1 && row.is_used == 0}
                        v-auth={'ADD_CHILD_GROUP'}>
                        关闭
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => closeClick(row, 2)}
                        vShow={row.status == 2}
                        vAuth={'ADD_CHILD_GROUP'}>
                        开启
                    </ElButton>
                    <ElPopover
                        placement="top-start"
                        width={200}
                        vSlots={{ reference: Reference2 }}
                        trigger="hover"
                        content="当前敏感词已在监控规则中配置，暂不可删除。"
                        vShow={row.is_used == 1}></ElPopover>
                    <ElButton vShow={row.is_used == 0} size="small" onClick={() => deleteline(row)} vAuth={'DEL'}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const defaultParams = reactive({
    keywords: '',
    status: '全部',
    group_id: pro.selectid
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const search = (data: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = {
        ...deepCopy({ ...state.searchParams }),
        ...data,
        group_id: pro.selectid
    };
    state.searchParams = deepCopy(currentParams.value);
    // state.searchParams = deepCopy(data)
};

/**
 * 清空专用
 */
const emptyFunc = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: pro.selectid };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v?: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(state.searchParams), group_id: addGroupingForm.group_id || pro.selectid };
    state.searchParams = deepCopy(currentParams.value);
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getSensitivelist;
};
// 选中表格 checkbox
const onSelect = (selection: any) => {
    allids.value = getSetionId('id', selection);
};
// 全选
const onSelectAll = (selection: any) => {
    allids.value = getSetionId('id', selection);
};
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
// 取消
const cancelHandel = () => {
    emit('cancel');
    appDialog.visible = false;
};
//删除 开启 关闭
const submitHandel = async () => {
    startLoading();
    try {
        if (appDialog.title == '删除提醒' || appDialog.title == '批量删除提醒') {
            const param = {
                id_arr: appDialog.title == '删除提醒' ? ids.value : allids.value
            };
            deleteSensitivelist(param)
                .then((res: any) => {
                    appDialog.visible = false;
                    ElMessage({ message: '删除成功', type: 'success' });
                    // initpage()
                    reset();
                    emit('refreshData');
                })
                .catch(() => {
                    endLoading();
                });
        } else if (appDialog.title == '开启提醒' || appDialog.title == '批量开启提醒') {
            const param = {
                id_arr: appDialog.title == '开启提醒' ? ids.value : allids.value
            };
            openSensitivelist(param)
                .then((res: any) => {
                    appDialog.visible = false;
                    ElMessage({ message: '开启成功', type: 'success' });
                    // initpage()
                    reset();
                })
                .catch(() => {
                    endLoading();
                });
        } else {
            const param = {
                id_arr: appDialog.title == '关闭提醒' ? ids.value : allids.value
            };
            closeSensitivelist(param)
                .then((res: any) => {
                    appDialog.visible = false;
                    ElMessage({ message: '关闭成功', type: 'success' });
                    // initpage()
                    reset();
                })
                .catch(() => {
                    endLoading();
                });
        }
    } catch (error) {
        endLoading();
    }
};
// 取消新增敏感词
const cancelnew = () => {
    newRuler.visible = false;
};
//确定新增敏感词
const submitnew = () => {
    startLoading();
    const reg = /\s+/;
    if (!addGroupingForm.words_name) {
        ElMessage({ message: '请填写敏感词', type: 'warning' });
        return;
    }
    const word = addGroupingForm.words_name.trim().split(reg);
    const param = {
        status: addGroupingForm.status ? 1 : 2,
        words_name: word,
        group_id: addGroupingForm.group_id
    };
    newSensitive(param)
        .then((res: any) => {
            newRuler.visible = false;
            ElMessage({
                message: res.msg,
                type: 'success'
            });
            reset();
            emit('refreshData', addGroupingForm.group_id);
        })
        .catch(() => {
            endLoading();
        });
};
const operate = (data: any) => {
    appDialog.visible = true;
    appDialog.title = data == 1 ? '批量开启提醒' : data == 2 ? '批量关闭提醒' : '批量删除提醒';
    content.value = data == 1 ? '确定开启所选关键词吗?' : data == 2 ? '确定关闭所选关键词吗？' : '确定删除所选内容吗？';
};
const newRuler = reactive({
    visible: false,
    title: `新增敏感词`,
    width: '500px',
    append: false,
    cancel: cancelnew,
    submit: submitnew,
    cancelText: '取消',
    submitText: '保存'
});
//打开新建敏感词弹框
const openWord = () => {
    newRuler.visible = true;
    addGroupingForm.group_id = pro.selectid == 'all' ? 0 : pro.selectid;
    addGroupingForm.words_name = '';
    getGroup();
};
const appDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '400px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
//获取表格列表
const getSensitive = (data?: any) => {
    const search = JSON.parse(JSON.stringify(searchData));
    search.status = search.status == '全部' ? 0 : search.status == '开启' ? 1 : 2;
    const parm = {
        ...search,
        page: data.page,
        page_size: data.page_size,
        group_id: pro.selectid
    };
    getSensitivelist(parm).then((res: any) => {
        store.dispatch('pageTotal', res.total);
        tableData.value = res.data;
    });
};
const initpage = async () => {
    emit('init');
};
initpage();
const getPagination = (data: any) => {
    page.page = data.page;
    page.page_size = data.page_size;
    initpage();
};
//搜索
const query = () => {
    initpage();
};
const remove = () => {
    searchData.keywords = '';
    searchData.status = '全部';
    initpage();
};
// 获取分组列表详情
const getGroup = () => {
    getGroupList({
        type: type.value
    }).then((res: any) => {
        groupData.value = res.data;
    });
};
const closeClick = (val: any, num: any) => {
    ids.value = [];
    appDialog.visible = true;
    appDialog.title = num == 2 ? '开启提醒' : '关闭提醒';
    content.value = num == 2 ? `确定要开启【${val.words_name}】吗？` : `确定要关闭【${val.words_name}】吗？`;
    ids.value.push(val.id);
};
const handleSelectionChange = (val: any) => {
    allids.value = [];
    val.forEach((item: { id: any }) => {
        allids.value.push(item.id);
    });
};

const deleteline = (val: any) => {
    ids.value = [];
    appDialog.visible = true;
    appDialog.title = '删除提醒';
    content.value = `确定要删除关键词【${val.words_name}】吗?`;
    ids.value.push(val.id);
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
// // 表格的自适应高度
// const getTableH = () => {
//   tabH.value = tableH('.table_box')
// }
onMounted(() => {
    reSize(getTableH);
    getTableH();
});
defineExpose({
    initpage,
    search,
    state
});
</script>
<style lang="scss" scoped>
.zw-table {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;

    :deep(.el-table) {
        flex: 1;

        .el-table__empty-block {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }
}

.demo-ruleForm {
    margin-top: 14px;
}

.search {
    background-color: #f9f9f9;
    padding: 16px;
}

.tablelist {
    .tips {
        padding: 9px;
        font-size: 12px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #969696;
        line-height: 16px;
        background: #f9f9f9;
    }

    .content {
        min-height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .table-top {
        display: flex;
        justify-content: flex-end;
        margin: 10px 0 15px;
    }
}
</style>
